<template>
  <div id="integralrule">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="40px">
      <!--基本信息-->
      <el-divider content-position="left">基础设置</el-divider>
      <el-form-item prop="moneyRate">
        <span>单次消费每&nbsp;&nbsp;&nbsp;</span>
        <el-input
          v-model="ruleForm.moneyRate"
          type="number"
          oninput="value=value.replace(/[^0-9.]/g,'')"
          class="input_edit"
          v-on:blur="moneyRateCheck()"
          style="text-align-last:right;width:300px;"
          placeholder=""
        >
          <template slot="append">元</template>
        </el-input>
        <span>&nbsp;&nbsp;&nbsp;积1积分</span>
      </el-form-item>
      <!--特殊商品设置-->
      <!-- <el-divider content-position="left">特殊商品设置</el-divider>
      <div style="margin-left:40px">
        <el-button type="primary" @click="showGoodsDialog()" icon="el-icon-plus" size="mini" style="margin:5px 0 20px 0">添加商品</el-button>
      </div>
      <div id="specialGoodsTable" style="margin:0 40px">
        <el-table
          ref="goodsTable"
          :data="goodsList"
          border
          style="width:100%;"
          v-loading="loading"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        >
          <el-table-column
              prop="goodsSeq"
              sortable
              column-key="goodsSeq"
              label="商品编码"
              align="center"
          ></el-table-column>
          <el-table-column
              prop="goodsName"
              sortable
              column-key="goodsName"
              label="商品名称"
              align="center"
          ></el-table-column>
          <el-table-column 
              prop="unitName" 
              sortable 
              label="计量单位" 
              align="center"
          ></el-table-column>
          <el-table-column prop="bonuspointMultiple" sortable label="积分倍数" align="center">
              <template slot-scope="scope">
                  <el-input
                    type="number"
                    :min="1"
                    oninput="value=value.replace(/[^0-9]/g,'')"
                    v-model="scope.row.bonuspointMultiple"
                    style="width:120px; text-align-last:right;"
                    v-on:blur="bonuspointMultipleCheck(scope.row,scope.$index)"
                    placeholder="请填写倍数"
                    :disabled="scope.row.runStatus == 3"
                  >
                  </el-input>
              </template>
          </el-table-column>
          <el-table-column label="开展状态" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.runStatus != 2 && scope.row.runStatus != 3">未开始</span>
              <span v-if="scope.row.runStatus == 2">进行中</span>
              <span v-if="scope.row.runStatus == 3">已结束</span>
            </template>
          </el-table-column>
          <el-table-column label="有效期" align="center" width="270">
            <template slot-scope="scope">
              <el-date-picker 
                v-model="scope.row.validDateRange"
                type="daterange"
                align="right"
                style="width:250px"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"
                @change="changeValidDate(scope.row,scope.$index)"
                :clearable="false"
                :disabled="scope.row.runStatus >= 2"
              ></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="活动说明" align="center">
            <template slot-scope="scope">
              <el-button size="mini" 
                type="primary"
                title="查看活动说明"
                @click="showActivityDescDialog(scope.row,scope.$index)" 
                v-if="scope.row.runStatus >= 2">查看活动说明</el-button>
              <el-button size="mini" 
                type="primary"
                title="添加活动说明"
                @click="showActivityDescDialog(scope.row,scope.$index)" 
                v-if="scope.row.runStatus < 2">添加活动说明</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button size="mini" @click="deleteGoodsItem(scope.row,scope.$index)" type="text">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div> -->
      <el-form-item style="width:100%;text-align:left;margin-top:40px;">
        <el-button type="primary" @click="submitForm('ruleForm')" :loading="submitLoading">保存积分设置</el-button>
      </el-form-item>
    </el-form>

    <!--添加特殊商品弹窗-->
    <el-dialog title="添加商品" :visible.sync="insertGoodsDialogVisible" width="60%">
      <div>
        <el-form :inline="true" :model="formInline2" class="demo-form-inline">
          <el-row :span="24">
            <el-col :span="24">
              <el-form-item label="商品编码：">
                <el-input v-model="formInline2.goodsSeq" clearable placeholder style="width:200px"></el-input>
              </el-form-item>
              <el-form-item label="商品名称：">
                <el-input v-model="formInline2.goodsName" clearable placeholder style="width:200px"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="search2()" size="mini" icon="el-icon-search">查询</el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="kong2()" size="mini" icon="el-icon-delete">清空</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="table2">
          <el-table ref="table2"
              tooltip-effect="dark"
              style="width: 100%"
              v-loading="loading2"
              :data="chooseGoodsList"
              @selection-change="handleSelectionChange2"
              border
              :header-cell-style="{background:'#eef1f6',color:'#606266'}"
          >
            <el-table-column type="selection" width="60" align="center" fixed disabled></el-table-column>
            <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
            <el-table-column prop="goodsPic" label="商品图片" align="center" width="150">
              <template slot-scope="scope">
                  <img
                    :src="scope.row.goodsPic"
                    v-if="scope.row.goodsPic !='' && scope.row.goodsPic !=null"
                    width="70"
                    height="50"
                  />
              </template>
            </el-table-column>
            <el-table-column prop="goodsSeq" label="商品编码" align="center" width="150" show-overflow-tooltip></el-table-column>
            <el-table-column prop="goodsName" label="商品名称" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="unitName" label="计量单位" align="center" width="100"></el-table-column>
            <el-table-column prop="salePrice" label="总部标准价" align="center" :formatter="fixData" width="100"></el-table-column>
            <el-table-column label="商品描述" align="center" show-overflow-tooltip width="300" >
              <template slot-scope="scope">
                <div v-html="scope.row.goodsDescribe"></div>
              </template>
            </el-table-column>
          </el-table>
          <div class="block" style="margin-top:22px;overflow:hidden">
            <el-pagination
              @size-change="handleSizeChange2"
              @current-change="handleCurrentChange2"
              :page-sizes="[5, 10, 20, 30, 50, 100, 150, 200]"
              :current-page="listQuery2.current"
              :page-size="listQuery2.size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total2"
            ></el-pagination>
          </div>
          <el-row>
            <el-col :span="24" style="text-align: center;margin-top: 30px">
              <el-button 
                type="info"
                @click="closeGoodsDialog()" 
                size="mini"
              >取 消</el-button>
              <el-button
                type="primary"
                @click="insertGoods()"
                size="mini"
              >确 认</el-button>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-dialog>

    <!--活动说明弹窗-->
    <el-dialog :title="activityDescDialogTitle" :visible.sync="activityDescDialogVisible" width="500px">
      <div>
        <el-row>
          <el-col :span="24" style="text-align: center;">
            <el-input
                type="textarea"
                v-model="editActivityDesc"
                :readonly="!editable"
                placeholder="请输入活动说明"
                maxlength="120"
                :autosize="{ minRows:4}"
                show-word-limit
                style="width:400px;"
            ></el-input>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: center;margin-top: 30px">
            <el-button 
              v-if="editable"
              type="info"
              @click="closeActivityDescDialog()" 
              size="mini"
            >取 消</el-button>
            <el-button
              type="primary"
              @click="insertActivityDesc()"
              size="mini"
            >确 认</el-button>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryBonuspointRuleConfig,
  queryChooseGoodsList,
  saveBonuspointRuleConfig
} from "@/api/integralrule";
import qs from "qs";

const curDateStr = function (){
  var curDate = new Date();
  var year = curDate.getFullYear();
  var month = curDate.getMonth() + 1;
  month = month > 9 ? month : "0" + month;
  var date = curDate.getDate();
  date = date > 9 ? date : "0" + date;
  return year + "-" + month + "-" + date;
}

const isMoney = function(rule, value, callback) {
  const reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
  if (value === null || value === undefined || value === "") {
    return callback(new Error("金额不能为空"));
  } else if (!reg.test(value)) {
    return callback(new Error("金额格式错误"));
  } else if (value <= 0) {
    return callback(new Error("金额不能小于等于0"));
  } else {
    callback();
  }
};

export default {
  data() {
    return {
      submitLoading: false,
      ruleForm: {
        uuid: null,
        moneyRate: 1.00,
        goodsCount: 0
      },
      rules: {
        moneyRate: [
          { required: true, message: "金额不能为空", trigger: "blur" },
          { validator: isMoney, trigger: "blur" }
        ],
      },
      loading: true,
      loading2: true,
      goodsList: [],//商品列表
      formInline2: {
        goodsName: "",
        goodsSeq: "",
        goodsTypeId: ""
      },//查询2
      total2: 0,
      listQuery2: {
        current: 1,
        size: 5
      },
      sort: "",
      order: "",
      insertGoodsDialogVisible: false,//挑选商品弹窗
      activityDescDialogVisible: false,//商品说明弹窗
      chooseGoodsList: [],//挑选商品列表
      batchSelGoods: [],//记录挑选多选商品id
      editGoodsListIndex: "",//记录编辑的商品列表序号
      editActivityDesc: "",//记录编辑的活动说明,
      activityDescDialogTitle: "",//活动说明弹窗的标题
      editable: false,//是否可编辑
      pickerOptions: {
        shortcuts: [
          {
            text: "未来3天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() + 3600 * 1000 * 24 * 3);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "未来一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "未来一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          }
        ],
        disabledDate(time){
          return time.getTime() < Date.now()-8.64e7   //如果当天可选，就不用减8.64e7
        }
      },
    };
  },

  mounted() {
    this.logininfo = localStorage.getItem("logininfo");
    this.orgSeq = JSON.parse(this.logininfo).orgSeq;
    this.queryBonuspointRuleConfig();
  },

  methods: {
    //获取积分配置
    queryBonuspointRuleConfig(){
      let data = {};
      queryBonuspointRuleConfig(data).then(res => {
        if(res.code == 1 && res.result != null){
          this.loading = false;
          this.ruleForm.uuid = res.result.uuid;
          this.ruleForm.moneyRate = res.result.moneyRate == null ? 1.00 : parseFloat(res.result.moneyRate).toFixed(2);
          this.goodsList = res.result.goodsList;
          this.ruleForm.goodsCount = this.goodsList.length  == 0 ? "" : this.goodsList.length;
          /*
          this.goodsList.forEach((item,i) => {
            item.bonuspointMultiple = parseFloat(item.bonuspointMultiple).toFixed(2);
          });
          */
        }
      });
    },
    //删除商品行
    deleteGoodsItem(row, index){
      this.goodsList.splice(index, 1);
      this.ruleForm.goodsCount = this.goodsList.length  == 0 ? "" : this.goodsList.length;
    },
    /******商品弹窗方法********/
    //显示挑选商品弹窗
    showGoodsDialog(){
      this.queryChooseGoodsList();
      this.insertGoodsDialogVisible = true;
    },
    //关闭挑选商品弹窗
    closeGoodsDialog(){
      this.insertGoodsDialogVisible = false;
      this.chooseGoodsList = [];
    },
    //挑选商品列表
    queryChooseGoodsList(){
      let includeGoods = [];
      this.goodsList.forEach((item, index) => {          
        includeGoods.push(item.goodsId);
      });
      let data = {
        current: this.listQuery2.current,
        size: this.listQuery2.size,
        condition: {
          activityId: this.ruleForm.uuid,
          includeGoods: includeGoods.length == 0 ? null : includeGoods,
          goodsName: this.formInline2.goodsName.trim(),
          goodsSeq: this.formInline2.goodsSeq.trim(),
          goodsTypeId: this.formInline2.goodsTypeId
        },
        ascs: [],
        descs: []
      };
      queryChooseGoodsList(data).then(res => {
        this.loading2 = false;
        this.chooseGoodsList = res.records;
        this.total2 = res.total;
      });
    },
    handleSizeChange2(val) {
      this.listQuery2.size = val;
      this.queryChooseGoodsList();
    },
    handleCurrentChange2(val) {
      this.listQuery2.current = val;
      this.queryChooseGoodsList();
    },
    //查询挑选商品
    search2(){
      this.listQuery2.current = 1;
      this.queryChooseGoodsList();
    },
    //重置挑选商品
    kong2(){
      this.formInline2.goodsSeq = "";
      this.formInline2.goodsName = "";
      this.formInline2.goodsTypeId = "";
    },
    //监听选择器
    handleSelectionChange2(val) {
      this.batchSelGoods = val;
    },
    //添加商品
    insertGoods(){
      if(this.batchSelGoods.length == 0){
         this.$message({
            showClose: true,
            message: "请先挑选纳入活动的商品",
            type: "info"
          });
          return false;
      }
      for (let index = 0; index < this.batchSelGoods.length; index++) {
        let row = this.batchSelGoods[index];
        let newGoods = {
          uuid: "",
          goodsId: row.uuid,
          goodsSeq: row.goodsSeq,
          goodsName: row.goodsName,
          goodsTypeName: row.goodsTypeName,
          unitName: row.unitName,
          salePrice: row.salePrice,
          bonuspointMultiple: 1,
          validDateRange: [curDateStr(), curDateStr()],
          beginDate: curDateStr(),
          endDate: curDateStr(),
          activityDesc: null,
          runStatus: 0//0新增 1未开始 2进行中 3已结束
        };
        this.goodsList.splice(0, 0, newGoods);
        this.ruleForm.goodsCount = this.goodsList.length  == 0 ? "" : this.goodsList.length;
      }
      this.closeGoodsDialog();
    },
    /*****活动说明弹窗*******/
    //显示弹窗
    showActivityDescDialog(row, index){
      this.editGoodsListIndex = index;
      this.editActivityDesc = row.activityDesc;
      if(row.runStatus >= 2){
        this.editable = false;
        this.activityDescDialogTitle = "查看活动说明";
      }else{
        this.editable = true;
        this.activityDescDialogTitle = "添加活动说明";
      }
      this.activityDescDialogVisible = true;
    },
    //关闭弹窗
    closeActivityDescDialog(){
      this.activityDescDialogVisible = false;
    },
    //添加活动说明
    insertActivityDesc(){
      if(this.editable){
        this.goodsList[this.editGoodsListIndex].activityDesc = this.editActivityDesc;
      }
      this.closeActivityDescDialog();
    },
    //保存积分规则
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let data = {
            uuid: this.ruleForm.uuid,
            moneyRate: this.ruleForm.moneyRate,
            goodsList: this.goodsList
          };
          this.submitLoading = true;
          saveBonuspointRuleConfig(data).then(res => {
            this.submitLoading = false;
            if(res.code == 1){
              this.$message({
                showClose: true,
                message: res.message,
                type: "success"
              });
              this.queryBonuspointRuleConfig();//刷新页面
            }else{
              this.$message({
                showClose: true,
                message: res.message,
                type: "error"
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    //单次积分额校验
    moneyRateCheck(){
      let val = this.ruleForm.moneyRate;
      if (val != null && $.trim(val) != "" && !isNaN(val)) {
        this.ruleForm.moneyRate = parseFloat(val).toFixed(2);
      }else{
        this.ruleForm.moneyRate = null;
      }
      return true;
    },
    //积分倍数校验
    bonuspointMultipleCheck(row, index) {
      let val = row.bonuspointMultiple;
      if (val === null || val === undefined || $.trim(val) === "") {
        this.$message({showClose: true, message: "积分倍数不能为空",type: "info"});
        val = 1;
      } else if (isNaN(val)){
        this.$message({showClose: true, message: "积分倍数格式错误",type: "info"});
        val = 1;
      } else if (val < 0){
        this.$message({showClose: true, message: "积分倍数应大于0",type: "info"});
        val = 1;
      } 
      this.goodsList[index].bonuspointMultiple = parseFloat(val).toFixed(0);
      return true;
    },
    //修改有效期
    changeValidDate(row, index){  
      if(row.validDateRange != null && row.validDateRange != undefined && row.validDateRange.length == 2){
        this.goodsList[index].beginDate = row.validDateRange[0];
        this.goodsList[index].endDate = row.validDateRange[1];
      }else{
        this.goodsList[index].beginDate = curDateStr();
        this.goodsList[index].endDate = curDateStr();
        this.goodsList[index].validDateRange = [curDateStr(),curDateStr()];
      }
    },
    //小数点
    fixData(row, column, cellValue, index) {
      if (cellValue != null && !isNaN(cellValue)) {
        return cellValue.toFixed(2);
      } else {
        return cellValue;
      }
    },
  }
};
</script>
<style  lang="less" scoped>
#integralrule /deep/ .el-dialog__body{
  padding-top:0px;
}
#integralrule /deep/ .el-input__inner[type='number']{
  padding:0;
}
</style>